package cn.billho.popcache.starter.config;

import cn.billho.popcache.core.api.ICacheApi;
import cn.billho.popcache.core.api.IGlobalLockApi;
import cn.billho.popcache.core.codec.DefaultResultParser;
import cn.billho.popcache.core.codec.IResultParse;
import cn.billho.popcache.core.codec.ISerialize;
import cn.billho.popcache.core.codec.JSONSerialize;
import cn.billho.popcache.core.impl.redis.RedisCacheImpl;
import cn.billho.popcache.core.impl.redis.RedisGlobalLockImpl;
import cn.billho.popcache.core.key.DefaultKeyGenerator;
import cn.billho.popcache.core.key.IKeyGenerate;
import cn.billho.popcache.starter.config.properties.PopCacheProperties;
import io.lettuce.core.api.StatefulRedisConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = {"cn.billho.popcache.starter.aop"})
public class PopCacheAutoConfig {
    @Autowired
    PopCacheProperties popCacheProperties;

    @Bean
    public IKeyGenerate getKeyGenerate(){
        return new DefaultKeyGenerator();
    }

    @Bean
    public IResultParse getResultParse(@Autowired ISerialize serialize ){
        return new DefaultResultParser(serialize);
    }

    @Bean
    public ISerialize getSerialize(){
        return new JSONSerialize();
    }

    @Bean
    public ICacheApi getCacheApi(@Autowired @Qualifier("popRedisConn") StatefulRedisConnection<String,String> mainRedisConnection){

        RedisCacheImpl redisCache = new RedisCacheImpl(mainRedisConnection, popCacheProperties.getRedis().isEnable());
        return redisCache;

    }

    @Bean
    public IGlobalLockApi getGlobalLockApi(@Autowired @Qualifier("popRedisConn") StatefulRedisConnection<String,String> mainRedisConnection){
        RedisGlobalLockImpl impl = new RedisGlobalLockImpl(mainRedisConnection);
        return impl;
    }
}
